package fun.xiefeihong.video.list.handle

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.security.web.authentication.rememberme.PersistentRememberMeToken
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository

class TokenHandle implements PersistentTokenRepository {

    static final Logger log = LoggerFactory.getLogger(TokenHandle.class)

    @Autowired
    RedisTemplate redisTemplate

    @Override
    void createNewToken(PersistentRememberMeToken token) {
        redisTemplate.opsForHash().put('token', token.series, token)
        log.info("createNewToken: ${token}")
    }

    @Override
    void updateToken(String series, String tokenValue, Date lastUsed) {
        def username = getTokenForSeries(series).username
        def token = new PersistentRememberMeToken(username, series, tokenValue, lastUsed)
        redisTemplate.opsForHash().put('token', series, token)
        log.info("updateToken: ${token}")
    }

    @Override
    PersistentRememberMeToken getTokenForSeries(String series) {
        def t = redisTemplate.opsForHash().get('token', series)
        log.info("getTokenForSeries: ${t}")
        def token
        if(t){
            token = new PersistentRememberMeToken(t.username, t.series, t.tokenValue, new Date(t.date))
        }
        token
    }

    @Override
    void removeUserTokens(String username) {
        redisTemplate.opsForHash().entries('token').each { series, token ->
            if(token.username == username){
                redisTemplate.opsForHash().delete('token', series)
                log.info("removeUserTokens: ${token}")
            }
        }
    }

}